package com.zzxx.photograph.service.impl;

import com.zzxx.photograph.dao.UserDao;
import com.zzxx.photograph.dao.impl.UserDaoImpl;
import com.zzxx.photograph.domain.User;
import com.zzxx.photograph.exception.LoginException;
import com.zzxx.photograph.service.UserService;
import com.zzxx.photograph.util.MailUtils;
import com.zzxx.photograph.util.UuidUtil;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public boolean register(User user) {
        String code = UuidUtil.getUuid();
        //调用dao保存用户
        user.setCode(code);
        user.setStatus("N");//设置激活状态
        int i = userDao.saveUser(user);
        if (i > 0) {
            //发送激活邮件
            String text = "请点击 <a href='http://localhost:8080/photograph/user/active?code=" + code + "'>这里</a>激活账号";
            String title = "账号激活";
            MailUtils.sendMail(user.getEmail(),text,title);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean usernameIsExists(String username) {
        return userDao.findUserByUsername(username) != null;
    }

    @Override
    public boolean activeUser(String code) {
        int i = userDao.updateUserStatusByCode(code);
        return i > 0;
    }

    @Override
    public User login(String username, String password) throws LoginException {
        User user = userDao.findByUsernameAndPwd(username, password);
        if (user == null) {
            throw new LoginException("账号/密码错误");
        } else if (user.getStatus().equals("N")) {
            throw new LoginException("账号未激活");
        }
        return user;
    }

    @Override
    //更新密码
    public void updatePasswordByUsername(String username, String password) {
        userDao.updatePasswordByUsername(username, password);
    }

    @Override
    public User getUserByUid(int uid) {
        return userDao.getUserByUid(uid);
    }

    @Override
    public void updateInfoByUid(String uid, User user) {
        userDao.update(uid, user);
    }

    @Override
    public void deleteUserByUid(String uid) {
        userDao.deleteUserByUid(uid);
    }

    @Override
    //联系我们
    public void sendMsg(String name, String email, String s) {
        String manageEmail = "1297405643@qq.com";
        String msg = "name:" + name +
                "<br>email:" + email +
                "<br>message" + s;
        MailUtils.sendMail(manageEmail, msg, "联系我们");
    }

    @Override
    //发送邮件
    public boolean sendEmail(String email) {
        //发送激活邮件
        String username = userDao.findUsernameByEmail(email);
        if (username != null) {
            String text = "请点击 <a href='http://localhost:8080/photograph/forgetpassword.html?username=" + username + "'>这里</a>修改密码";
            String title = "修改密码";
            MailUtils.sendMail(email, text, title);
            return true;
        } else {
            return false;
        }
    }
}
